package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
)

type DmsUser struct {
	Id       int    `orm:"column(id);auto"`
	Uname    string `orm:"column(uname);size(20)"`
	Pwd      string `orm:"column(pwd);size(32)"`
	Status   int    `orm:"column(status)"`
	UserName string `orm:"column(UserName)"`
}
type UserChangePass struct {
	Id             int    `orm:"column(id);auto" form:"id"  json:"id"`
	Uname          string `form:"uname" orm:"column(uname)" json:"uname"`
	Uid            string `form:"uid" orm:"column(uid)" json:"uid"`
	OldPass        string `form:"oldpass" orm:"column(oldpass)" json:"oldpass"`
	NewPass        string `form:"newpass" orm:"column(newpass)" json:"newpass"`
	Newpassagain   string `form:"newpassagain" orm:"column(newpassagain)" json:"newpassagain"`
	LastModifyTime string `form:"lastmodifytime" orm:"column(lastmodifytime)" json:"lastmodifytime"`
}

const tableName = "dms_user"

// table name func
func (u *DmsUser) TableName() string {
	return tableName
}

func init() {
	orm.RegisterModel(new(DmsUser))
}

// add user
func AddDmsUser(u *DmsUser) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(u)
	return
}

// get user by name and pwd
func GetUserByNameAndPwd(uname, pwd string) (users []*DmsUser) {
	o := orm.NewOrm()
	//err := o.Raw("select * from ? where status=1 uname=? and pwd=?", tableName, uname, pwd).QueryRows(&users)
	user := new(DmsUser)
	qs := o.QueryTable(user)
	qs.Filter("uname", uname).Filter("pwd", pwd).Filter("status", 1).All(&users)
	if len(users) == 0 {
		return nil
	}
	return users
}
func UpdateUserById(m *DmsUser) (err error) {
	o := orm.NewOrm()
	v := DmsUser{Id: m.Id}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("user pass updated in database:", num)
		}
	}
	return
}
